// 通用工具函数
class AppUtils {
    constructor() {
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.setupTooltips();
        this.setupModals();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 全局点击事件
        document.addEventListener('click', (e) => {
            this.handleClickOutside(e);
        });

        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeAllModals();
            }
        });

        // 窗口大小改变事件
        window.addEventListener('resize', () => {
            this.handleResize();
        });
    }

    // 设置工具提示
    setupTooltips() {
        const tooltips = document.querySelectorAll('[data-tooltip]');
        tooltips.forEach(tooltip => {
            tooltip.addEventListener('mouseenter', (e) => {
                this.showTooltip(e.target);
            });
            tooltip.addEventListener('mouseleave', (e) => {
                this.hideTooltip(e.target);
            });
        });
    }

    // 设置模态框
    setupModals() {
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            const closeBtn = modal.querySelector('[data-close-modal]');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    this.closeModal(modal);
                });
            }

            // 点击背景关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.closeModal(modal);
                }
            });
        });
    }

    // 显示工具提示
    showTooltip(element) {
        const tooltip = element.getAttribute('data-tooltip');
        if (!tooltip) return;

        const tooltipEl = document.createElement('div');
        tooltipEl.className = 'tooltip-content';
        tooltipEl.textContent = tooltip;
        tooltipEl.style.cssText = `
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background-color: #1f2937;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.75rem;
            white-space: nowrap;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.2s ease;
            margin-bottom: 0.5rem;
        `;

        element.appendChild(tooltipEl);
        setTimeout(() => {
            tooltipEl.style.opacity = '1';
        }, 10);
    }

    // 隐藏工具提示
    hideTooltip(element) {
        const tooltipEl = element.querySelector('.tooltip-content');
        if (tooltipEl) {
            tooltipEl.style.opacity = '0';
            setTimeout(() => {
                tooltipEl.remove();
            }, 200);
        }
    }

    // 关闭模态框
    closeModal(modal) {
        modal.classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    // 关闭所有模态框
    closeAllModals() {
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            this.closeModal(modal);
        });
    }

    // 处理点击外部
    handleClickOutside(e) {
        // 处理下拉菜单等外部点击
    }

    // 处理窗口大小改变
    handleResize() {
        // 处理响应式布局
    }

    // 显示通知
    showNotification(message, type = 'success', duration = 3000) {
        console.log('调用了app.js中的showNotification')
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            color: white;
            font-weight: 500;
            z-index: 1000;
            animation: slideIn 0.3s ease-out;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        // 设置不同类型的背景色
        if (type === 'success') {
            notification.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
        } else if (type === 'error') {
            notification.style.background = 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)';
        } else if (type === 'warning') {
            notification.style.background = 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)';
        } else {
            notification.style.background = 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)';
        }
        
        document.body.appendChild(notification);
        
        // 动画显示
        setTimeout(() => {
            notification.style.opacity = '1';
        }, 10);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, duration);
    }

    // 确认对话框
    showConfirm(message, onConfirm, onCancel = null) {
        const modal = document.createElement('div');
        modal.className = 'modal fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center';
        modal.innerHTML = `
            <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
                <div class="p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">确认</h3>
                    <p class="text-gray-600 mb-6">${message}</p>
                    <div class="flex justify-end space-x-3">
                        <button class="cancel-btn px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                            取消
                        </button>
                        <button class="confirm-btn px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                            确认
                        </button>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        document.body.style.overflow = 'hidden';

        const cancelBtn = modal.querySelector('.cancel-btn');
        const confirmBtn = modal.querySelector('.confirm-btn');

        const cleanup = () => {
            modal.remove();
            document.body.style.overflow = 'auto';
        };

        cancelBtn.addEventListener('click', () => {
            cleanup();
            if (onCancel) onCancel();
        });

        confirmBtn.addEventListener('click', () => {
            cleanup();
            if (onConfirm) onConfirm();
        });

        // ESC键关闭
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                cleanup();
                if (onCancel) onCancel();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);
    }

    // 加载指示器
    showLoading(target = document.body) {
        const loader = document.createElement('div');
        loader.className = 'loading-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        loader.innerHTML = `
            <div class="bg-white rounded-lg p-6 flex items-center space-x-3">
                <div class="loading-spinner"></div>
                <span class="text-gray-700">加载中...</span>
            </div>
        `;
        
        if (target === document.body) {
            document.body.appendChild(loader);
        } else {
            target.style.position = 'relative';
            loader.style.position = 'absolute';
            loader.classList.remove('fixed');
            target.appendChild(loader);
        }
        
        return loader;
    }

    // 隐藏加载指示器
    hideLoading(loader) {
        if (loader && loader.parentNode) {
            loader.remove();
        }
    }

    // API请求封装
    async apiRequest(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
            }
        };

        // 获取token
        const token = this.getToken();
        if (token) {
            defaultOptions.headers['Authorization'] = `Bearer ${token}`;
        }

        const finalOptions = {
            ...defaultOptions,
            ...options,
            headers: {
                ...defaultOptions.headers,
                ...options.headers
            }
        };

        try {
            const response = await fetch(url, finalOptions);
            
            // 处理401错误（token过期）
            if (response.status === 401) {
                this.showNotification('登录已过期，请重新登录', 'error');
                setTimeout(() => {
                    window.location.href = '/web/login';
                }, 2000);
                throw new Error('登录已过期');
            }
            
            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.detail || data.message || '请求失败');
            }

            return data;
        } catch (error) {
            console.error('API请求失败:', error);
            // 只在非404错误时显示通知，404错误在仪表板上是正常的（没有任务）
            if (!error.message.includes('Task not found') && !error.message.includes('404') && !error.message.includes('登录已过期')) {
                // this.showNotification(error.message || '请求失败', 'error');
                console.log(error.message || '请求失败');
            }
            throw error;
        }
    }

    // 获取token
    getToken() {
        // 从URL参数获取
        const urlParams = new URLSearchParams(window.location.search);
        const token = urlParams.get('token');
        
        // 从localStorage获取（备用）
        if (!token) {
            return localStorage.getItem('auth_token');
        }
        
        return token;
    }

    // 保存token
    saveToken(token) {
        localStorage.setItem('auth_token', token);
    }

    // 清除token
    clearToken() {
        localStorage.removeItem('auth_token');
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 格式化日期
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }

    // 格式化相对时间
    formatRelativeTime(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        
        const minute = 60 * 1000;
        const hour = minute * 60;
        const day = hour * 24;
        const week = day * 7;
        const month = day * 30;
        const year = day * 365;
        
        if (diff < minute) {
            return '刚刚';
        } else if (diff < hour) {
            return Math.floor(diff / minute) + '分钟前';
        } else if (diff < day) {
            return Math.floor(diff / hour) + '小时前';
        } else if (diff < week) {
            return Math.floor(diff / day) + '天前';
        } else if (diff < month) {
            return Math.floor(diff / week) + '周前';
        } else if (diff < year) {
            return Math.floor(diff / month) + '个月前';
        } else {
            return Math.floor(diff / year) + '年前';
        }
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    // 复制到剪贴板
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showNotification('已复制到剪贴板', 'success');
        } catch (err) {
            // 备用方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showNotification('已复制到剪贴板', 'success');
        }
    }

    // 下载文件
    downloadFile(url, filename) {
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    // 验证表单
    validateForm(form) {
        const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
        let isValid = true;
        
        inputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('border-red-500');
                isValid = false;
            } else {
                input.classList.remove('border-red-500');
            }
        });
        
        return isValid;
    }

    // 清理表单
    clearForm(form) {
        form.reset();
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            input.classList.remove('border-red-500');
        });
    }

    // 检查权限
    hasPermission(requiredRole) {
        const user = this.getCurrentUser();
        if (!user) return false;
        
        if (user.role === 'admin') return true;
        if (user.role === requiredRole) return true;
        
        return false;
    }

    // 获取当前用户
    getCurrentUser() {
        const userStr = localStorage.getItem('current_user');
        if (userStr) {
            try {
                return JSON.parse(userStr);
            } catch (e) {
                return null;
            }
        }
        return null;
    }

    // 保存当前用户
    saveCurrentUser(user) {
        localStorage.setItem('current_user', JSON.stringify(user));
    }

    // 检查登录状态
    checkLoginStatus() {
        const token = this.getToken();
        
        if (!token) {
            // 跳转到登录页
            const currentPath = window.location.pathname;
            if (currentPath !== '/web/login') {
                window.location.href = '/web/login';
            }
            return false;
        }
        
        return true;
    }

    // 登出
    logout() {
        this.clearToken();
        localStorage.removeItem('current_user');
        window.location.href = '/web/login';
    }

    // 初始化主题
    initTheme() {
        const savedTheme = localStorage.getItem('theme') || 'light';
        document.documentElement.setAttribute('data-theme', savedTheme);
    }

    // 切换主题
    toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
    }
}

// 创建全局实例
window.app = new AppUtils();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 只在需要时检查登录状态
    // 如果URL中没有token且localStorage中也没有token，才跳转到登录页
    const urlParams = new URLSearchParams(window.location.search);
    const hasTokenInUrl = urlParams.has('token');
    const hasTokenInStorage = localStorage.getItem('auth_token') !== null;
    
    if (!hasTokenInUrl && !hasTokenInStorage && !window.location.pathname.includes('/login')) {
        window.location.href = '/web/login';
    }
    
    // 初始化主题
    window.app.initTheme();
});

// 导出工具函数
window.showNotification = (message, type, duration) => window.app.showNotification(message, type, duration);
window.showConfirm = (message, onConfirm, onCancel) => window.app.showConfirm(message, onConfirm, onCancel);
window.showLoading = (target) => window.app.showLoading(target);
window.hideLoading = (loader) => window.app.hideLoading(loader);
window.apiRequest = (url, options) => window.app.apiRequest(url, options);
window.formatFileSize = (bytes) => window.app.formatFileSize(bytes);
window.formatDate = (dateString) => window.app.formatDate(dateString);
window.copyToClipboard = (text) => window.app.copyToClipboard(text);
window.downloadFile = (url, filename) => window.app.downloadFile(url, filename);
window.hasPermission = (role) => window.app.hasPermission(role);
window.logout = () => window.app.logout();